package com._21cn._admin.authority;

import com._21cn.cms.common.Constants;
import com._21cn.framework.http.HttpRequestInfo;
import com._21cn.framework.utils.StringUtil;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by Administrator on 2017/9/9.
 */
public class AdminAuthFilter implements Filter {

    private boolean isAllowed = false;

    private String loginUrl = "";

    private String excludeUrl = "";

    private String[] excludeUrlArray = null;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        this.loginUrl = filterConfig.getInitParameter("loginUrl");
        this.excludeUrl = filterConfig.getInitParameter("excludeUrl");
        if (!StringUtil.isEmpty(this.excludeUrl))
            this.excludeUrlArray = this.excludeUrl.split(",");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse)servletResponse;
        HttpRequestInfo reqInfo = new HttpRequestInfo(request);

        String requestUrl = request.getRequestURL().toString();
        if (this.excludeUrlArray != null) {
            for (int i = 0; i < this.excludeUrlArray.length; i++) {
                if (requestUrl.indexOf(this.excludeUrlArray[i]) >= 0) {
                    filterChain.doFilter(servletRequest, servletResponse);
                    return;
                }
            }
        }

        String cookieValue=reqInfo.getCookieValue(Constants.ADMIN_AUTH_KEY, "");
        if(StringUtil.isEmpty(cookieValue)){
            isAllowed = false;
        }else {
            if( cookieValue.equals(Constants.ADMIN_AUTH_VALUE)){
                isAllowed = true;
            }else {
                isAllowed = false;
            }
        }
        if( !isAllowed ){
            response.sendRedirect(loginUrl);
        }else {
            filterChain.doFilter(servletRequest, servletResponse);
        }

    }

    @Override
    public void destroy() {

    }
}
